package com.gree.flowable.modeler.security;

import com.gree.framework.entity.CusUserDetails;
import org.apache.commons.lang3.StringUtils;
import org.flowable.ui.common.properties.FlowableCommonAppProperties;
import org.flowable.ui.common.tenant.DefaultTenantProvider;
import org.flowable.ui.common.tenant.TenantProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

/**
 * 覆盖flowable自带的租户获取方法，如果你日后发现多租户平时在线保存模型也有bug，那重写modelService吧~
 */
@Component
@Primary
public class MyTenantProvider implements TenantProvider {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTenantProvider.class);

    private String tenantId;

    public MyTenantProvider(FlowableCommonAppProperties commonAppProperties) {
        super();
        String configuredTenantId = commonAppProperties.getTenantId();
        if(! StringUtils.isBlank(configuredTenantId)) {
            // trim whitespace as trailing whitespace are possible in properties files and easy to do
            configuredTenantId = configuredTenantId.trim();

            // quotes can help solve whitespace issues
            LOGGER.debug("Found configured tenantId: '{}'", configuredTenantId);

            this.tenantId = configuredTenantId;
        }
    }

    @Override
    public String getTenantId() {
//        if(tenantId != null) {
//            LOGGER.debug("Using configured tenantId: '{}'", tenantId);
//            return tenantId;
//        }
//
//        User user = SecurityUtils.getCurrentUserObject();
//        if(user != null) {
//            // quotes can help solve whitespace issues, trimming here would not
//            // help solve the problem at source which is in user database
//            LOGGER.debug("Using user tenantId: '{}'", tenantId);
//
//            return user.getTenantId();
//        }
//
//        LOGGER.debug("No tenantId");

        String clientId = com.gree.framework.utils.SecurityUtils.getClientId();
        CusUserDetails user = com.gree.framework.utils.SecurityUtils.getUser();
        if ("gscm_client".equals(clientId)){
            return null;
        }else {
            String systemName = user.getUsername();
            return systemName;
        }
//        return null;
    }
}
